package cn.tao.hrm.controller;


import cn.tao.hrm.exception.ErrorCode;
import cn.tao.hrm.properties.AliyunOssProperties;
import cn.tao.hrm.util.AjaxResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

//阿里云对象存储
@RestController
@RequestMapping("/aliyunoss")
public class AliOssController {

    @Autowired
    private AliyunOssProperties properties;

    //签名方法
    @GetMapping("/sign")
    public AjaxResult sign(){
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessId = properties.getAccessKey();
        String accessKey = properties.getSecretKey();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        //https://lxy-hrm-1115.oss-cn-chengdu.aliyuncs.com
        String endpoint = properties.getEndpoint();
        // 填写Host名称，格式为https://bucketname.endpoint。
        String host = "https://" + properties.getBucketName() +
                        "."+properties.getEndpoint();
         // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String dir = properties.getDir();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

            return AjaxResult.me().setResultObj(respMap);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            e.printStackTrace();
            System.out.println(e.getMessage());
            return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode());
        } finally {
            ossClient.shutdown();
        }
    }
}
